package com.czk.gulimall.seckill.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.czk.common.to.mq.QuickOrderTo;
import com.czk.common.utils.R;
import com.czk.gulimall.seckill.feign.CouponFeignService;
import com.czk.gulimall.seckill.feign.ProductFeignService;
import com.czk.gulimall.seckill.interceptor.LoginUserInterceptor;
import com.czk.gulimall.seckill.service.SeckillService;
import com.czk.gulimall.seckill.to.SeckillSkuRedisTo;
import com.czk.gulimall.seckill.vo.SeckillSessionWithSkus;
import com.czk.gulimall.seckill.vo.SkuInfoVo;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RSemaphore;
import org.redisson.api.RedissonClient;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @Author:ChenZhangKun
 * @Date: 2022/6/14 22:02
 */
@Slf4j
@Service
public class SeckillServiceImpl implements SeckillService {

    @Autowired
    private CouponFeignService couponFeignService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Autowired
    private RedissonClient redissonClient;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Autowired
    private ProductFeignService productFeignService;
    private static final String SESSIONS_CACHE_PREFIX = "seckill:sessions:";
    private static final String SKUKILL_CACHE_PREFIX = "seckill:skus:";
    private static final String SKU_STOCK_SEMAPHORESKUS = "sekill:stock:";

    @Override
    public void uploadSeckill() {
        // 重复上架无需处理
        R r = couponFeignService.getLatest3DaysSession();
        JSONArray jsonArray = (JSONArray) r.getData("data", new TypeReference() {
        });
        List<SeckillSessionWithSkus> list = jsonArray.toJavaList(SeckillSessionWithSkus.class);
        //
        saveSessionInfos(list);
        saveSessionSkuInfos(list);
    }


    @Override
    public List<SeckillSkuRedisTo> getCurrentSeckillSkus() {
        // redis中获取
        // 1 确定当前时间属于哪个秒杀场次
        long time=System.currentTimeMillis();
        // 拿到key数据
        Set<String> keys = stringRedisTemplate.keys(SESSIONS_CACHE_PREFIX + "*");
        for (String key : keys) {
            String replace = key.replace(SESSIONS_CACHE_PREFIX, "");
            String[] s = replace.split("-");
            long start=Long.parseLong(s[0]);
            long end=Long.parseLong(s[1]);
            if (time >=start&&time<=end){
                List<String> range = stringRedisTemplate.opsForList().range(key, -100, 100);
                BoundHashOperations<String, String, Object> hashOps = stringRedisTemplate.boundHashOps(SKU_STOCK_SEMAPHORESKUS);
                List<Object> list = hashOps.multiGet(range);
                if (list!=null){
                    List<SeckillSkuRedisTo> collect = list.stream().map(item -> {
                        SeckillSkuRedisTo redisTo = JSON.parseObject(item.toString(), SeckillSkuRedisTo.class);
                        return redisTo;
                    }).collect(Collectors.toList());
                    return collect;
                }

            }
        }
        // 2 获取这个秒杀场次需要的所有的商品信息
        return null;
    }

    private void saveSessionSkuInfos(List<SeckillSessionWithSkus> list) {
        list.stream().forEach(x -> {
            BoundHashOperations<String, Object, Object> ops = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);
            x.getRelationSkus().stream().forEach(seckillSkuVo -> {
                // 随机码
                String token = UUID.randomUUID().toString().replace("-", "");
                if (!ops.hasKey(seckillSkuVo.getId().toString()+"_"+seckillSkuVo.getPromotionSessionId())) {
                    // 缓存商品
                    SeckillSkuRedisTo redisTo = new SeckillSkuRedisTo();
                    R info = productFeignService.info(seckillSkuVo.getSkuId());
                    if (info.getCode() == 0) {
                        JSONObject jsonObject = (JSONObject) info.getData("skuInfo", new TypeReference<SkuInfoVo>() {
                        });
                        SkuInfoVo skuInfoVo = jsonObject.toJavaObject(SkuInfoVo.class);
                        redisTo.setSkuInfoVo(skuInfoVo);
                    }
                    // 秒杀信息
                    BeanUtils.copyProperties(seckillSkuVo, redisTo);
                    // 秒杀时间
                    redisTo.setStartTime(x.getStartTime().getTime());
                    redisTo.setEndTime(x.getEndTime().getTime());
                    ops.put(seckillSkuVo.getId().toString(), JSON.toJSONString(redisTo));

                }
                // 信号量，限流
                // 如果当前·1场次的库存信息已经上架就不需要上架

                RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORESKUS + token);
                semaphore.trySetPermits(seckillSkuVo.getSeckillCount().intValue());
            });
        });
    }

    /**
     * 保存到redis
     *
     * @param list
     */
    private void saveSessionInfos(List<SeckillSessionWithSkus> list) {
        list.stream().forEach(session -> {
            long startTime = session.getStartTime().getTime();
            long endTime = session.getEndTime().getTime();
            String key = startTime + "_" + endTime;
            Boolean hasKey = stringRedisTemplate.hasKey(key);
            if (!hasKey) {
                List<String> collect = session.getRelationSkus().stream().map(item -> item.getPromotionSessionId()+"_"+item.getSkuId().toString()).collect(Collectors.toList());
                stringRedisTemplate.opsForList().leftPushAll(SESSIONS_CACHE_PREFIX + key, collect);
            }

        });

    }

    @Override
    public String kill(String killId, String key, Integer num) {
        // 合法性校验
        BoundHashOperations<String, String, String> hasOps = stringRedisTemplate.boundHashOps(SKUKILL_CACHE_PREFIX);

        String s = hasOps.get(killId);
        if (StringUtils.isEmpty(s)){
            return null;
        }else {
            SeckillSkuRedisTo redis = JSON.parseObject(s, SeckillSkuRedisTo.class);
            // 合法性校验
            Long startTime = redis.getStartTime();
            Long endTime = redis.getEndTime();
            long time = System.currentTimeMillis();
            long ttl=endTime-time;
            if (time>=startTime&&time<endTime){
                // 校验随机码
                String randomCode = redis.getRandomCode();
                Long skuId = redis.getSkuId();
                if (Objects.equals(randomCode,key)&&Objects.equals(skuId,killId)){
                    // 验证购物数量
                    BigDecimal seckillLimit = redis.getSeckillLimit();
                    int intValue = seckillLimit.intValue();
                    if (num<=intValue){
                        // 验证·1这个人是否已经购买过
                        String redisKey= LoginUserInterceptor.loginUser.get().getId()+"_"+skuId;
                        // 自动过期
                        Boolean aBoolean = stringRedisTemplate.opsForValue().setIfAbsent(redisKey, num + "", ttl, TimeUnit.MILLISECONDS);
                        if (aBoolean){
                            // 站位成功
                            // 分布式信号量进行减
                            RSemaphore semaphore = redissonClient.getSemaphore(SKU_STOCK_SEMAPHORESKUS + randomCode);
                            try {
                                boolean b = semaphore.tryAcquire(num, 100, TimeUnit.MILLISECONDS);
                                // 秒杀成功，进行下单
                                String timeId = IdWorker.getTimeId();
                                QuickOrderTo orderTo = new QuickOrderTo();
                                orderTo.setOrderSn(timeId);
                                orderTo.setMemberId(LoginUserInterceptor.loginUser.get().getId());
                                orderTo.setPromotionSessionId(redis.getPromotionSessionId());
                                orderTo.setSkuId(redis.getSkuId());
                                orderTo.setNum(redis.getSeckillCount().intValue());
                                rabbitTemplate.convertAndSend("order-event-exchange","order.seckill.order",orderTo);

                                return timeId;
                            } catch (InterruptedException e) {
                                return null;
                            }
                        }else {
                            return null;
                        }
                    }
                }else {
                    return null;
                }

            }else {

            }
        }
        return null;
    }
}
